package com.example.hosptial.service.impl;

import com.example.hosptial.model.enity.Admin;
import com.example.hosptial.model.view.DoctorView;
import com.example.hosptial.repository.AdminRepository;
import com.example.hosptial.repository.DoctorViewRepository;
import com.example.hosptial.service.AuthService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
@Transactional
public class AuthServiceImpl implements AuthService {
    @Autowired
    private DoctorViewRepository doctorViewRepository;

    @Autowired
    private AdminRepository adminRepository;

    @Override
    public Admin adminLogin(String username, String password) {
        if (username == null || password == null ||
            username.trim().isEmpty() || password.trim().isEmpty()) {
            return null;
        }

        return adminRepository.findByUsernameAndPassword(username.trim(), password)
                .orElse(null);
    }

    @Override
    public void createAdminSession(HttpSession session, Admin admin) {
        if (session != null && admin != null) {
            session.setAttribute("admin", admin);
            session.setAttribute("userType", "admin");
        }
    }

    @Override
    public void logout(HttpSession session) {
        if (session != null) {
            session.invalidate();
        }
    }

    @Override
    public boolean validateAdminSession(HttpSession session) {
        if (session == null) {
            return false;
        }

        Object userType = session.getAttribute("userType");
        return "admin".equals(userType) && session.getAttribute("admin") != null;
    }

    @Override
    public Optional<DoctorView> doctorLogin(String doctorId, String password) {
        // 参数验证
        if (doctorId == null || doctorId.trim().isEmpty()) {
            throw new IllegalArgumentException("医生工号不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }

        return doctorViewRepository.validateLogin(doctorId.trim(), password);
    }

    @Override
    public boolean isDoctorLoggedIn(String doctorId) {
        // 可以通过Session或Token实现，这里简单返回
        return true;
    }

    @Override
    public void doctorLogout(String doctorId) {
        // 可以清理Session或Token
    }
}